package com.yitao.cms.service.overseasLogisticsInfo;

import com.querydsl.core.types.Order;
import com.querydsl.core.types.OrderSpecifier;
import com.skipper.base.bean.CommonStatus;
import com.skipper.base.bean.DataOutput;
import com.skipper.base.bean.PagedInput;
import com.skipper.base.bean.PagedOutput;
import com.skipper.base.data.querydsl.PredicateBuilder;
import com.skipper.base.service.GenericEntityService;
import com.yitao.cms.dto.overseasLogistics.OverseasLogisticsErrorDto;
import com.yitao.cms.enums.OverseasLogisticsEnums;
import com.yitao.cms.model.overseasLogistics.OverseasLogisticsErrorModel;
import com.yitao.cms.model.overseasLogistics.QOverseasLogisticsErrorModel;
import com.yitao.cms.utils.BaseUtils;
import com.yitao.cms.utils.DateUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.persistence.EntityManager;
import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Kien
 * @ClassName OverseasLogisticsErrorService
 * @date 2019/4/12 16:52
 */
@Service
public class OverseasLogisticsErrorService extends GenericEntityService<OverseasLogisticsErrorModel, OverseasLogisticsErrorDto, QOverseasLogisticsErrorModel> {
    @Autowired
    private OverseasLogisticsInfoService overseasLogisticsInfoService;

    public OverseasLogisticsErrorService(EntityManager entityManager) {
        super(entityManager);
    }

    /**
     * 描述: 新增
     *
     * @param overseasLogisticsErrorModel 回调异常信息
     * @return
     * @auther: Kien
     */
    @Transactional
    public DataOutput saveOverseasLogisticsError(OverseasLogisticsErrorModel overseasLogisticsErrorModel){
        if(overseasLogisticsErrorModel == null) {
            return new DataOutput(CommonStatus.BAD_REQUEST);
        }
        OverseasLogisticsErrorModel result = repository.save(overseasLogisticsErrorModel);
        return new DataOutput(result);
    }

    /**
     * 描述: 异常表信息展示
     * @param pageNo 当前页面
     * @param  pageSize 每页显示条数
     *
     * @return
     * @auther: Kien
     */
    public PagedOutput<OverseasLogisticsErrorDto> findOverseasLogisticsError(Integer pageNo, Integer pageSize) {
        PagedInput pagedInput = new PagedInput(pageSize, pageNo);
        try {
            PagedOutput<OverseasLogisticsErrorModel> pageOutput = repository.pagingList(PredicateBuilder.conjunction()
                    .and(() -> Q.handlingStatus.eq(OverseasLogisticsEnums.HANDLING_STATUS.UNTREATED.getCode()))
                    .get(), pagedInput, new OrderSpecifier<>(Order.DESC, Q.createTime));
            List<OverseasLogisticsErrorDto> list = new ArrayList<>();
            if(pageOutput != null && pageOutput.getData().size() != 0) {
                list = pageOutput.getData().stream().map(it ->{
                    OverseasLogisticsErrorDto overseasLogisticsErrorDto = new OverseasLogisticsErrorDto();
                    BeanUtils.copyProperties(it, overseasLogisticsErrorDto);
                    overseasLogisticsErrorDto.setStatusString(OverseasLogisticsEnums.p2Status.getMsgByCode(it.getStatus().toString()));
                    overseasLogisticsErrorDto.setCreateTimeStr(DateUtils.getDateSecondFormat(it.getCreateTime())); // 格式化时间
                    return overseasLogisticsErrorDto;
                }).collect(Collectors.toList());

            }
            return new PagedOutput(pagedInput, pageOutput.getTotalElements(), list);
        } catch (Exception e) {
            logger.error("获取异常信息数据异常", e);
            return new PagedOutput(pagedInput, 0, new ArrayList());
        }
    }

    /**
     * 描述: 异常表信息展示
     * @param overseaExpressNo 商家发货快递编号
     *
     * @return
     * @auther: Kien
     */
    @Transactional
    public void updateHandingStatusByOverseaExpressNo(String overseaExpressNo){
        if(!StringUtils.isBlank(overseaExpressNo)) {
            logger.info("overseaExpressNo:{},state:{}",overseaExpressNo,OverseasLogisticsEnums.HANDLING_STATUS.PROCESSED.getCode());
          Integer result =  repository.updateByWhere(Q.overseaExpressNo.eq(overseaExpressNo), it ->it.set(Q.handlingStatus, OverseasLogisticsEnums.HANDLING_STATUS.PROCESSED.getCode()));
        }
    }

    /**
     * 描述: 手动推送预报
     * @param id 异常信息id
     *
     * @return
     * @auther: Kien
     */
    @Transactional
    public DataOutput artificialPush(Long id) {
        // 根据异常信息id获取境外物流信息表id
        OverseasLogisticsErrorModel overseasLogisticsErrorModel = repository.findOne(Q.id.eq(id));
        if(overseasLogisticsErrorModel == null) {
            return new DataOutput(CommonStatus.NOT_FOUND);
        }
        Long overseasLogisticsInfoId1 = overseasLogisticsErrorModel.getOverseasLogisticsInfoId();
        if(overseasLogisticsInfoId1 != null) {
            DataOutput dataOutput = overseasLogisticsInfoService.httpShipmentsById(overseasLogisticsInfoId1.toString());
            if(dataOutput.getStatus().equals("0")) {
                repository.updateByWhere(Q.id.eq(id), it ->it.set(Q.handlingStatus, OverseasLogisticsEnums.HANDLING_STATUS.PROCESSED.getCode()));
            }
            return new DataOutput();
        }
        return new DataOutput(CommonStatus.BAD_REQUEST);
    }
}
